from dataclasses import dataclass
from typing import BinaryIO
import io

import sniff

@dataclass
class RawDecoder:
    rd: BinaryIO
    audio_ext: str = ""

    def validate(self) -> None:
        header = self.rd.read(16)
        if len(header) < 16:
            raise ValueError("read file header failed")
        self.rd.seek(0, io.SEEK_SET)
        self.audio_ext = sniff.audio_extension(header)
        if not self.audio_ext:
            raise ValueError("raw: sniff audio type failed")

    def read(self, size: int = -1) -> bytes:
        return self.rd.read(size)

def register_decoder():
    from .dispatch import register_decoder
    register_decoder("mp3", True, RawDecoder)
    register_decoder("flac", True, RawDecoder)
    register_decoder("ogg", True, RawDecoder)
    register_decoder("m4a", True, RawDecoder)
    register_decoder("wav", True, RawDecoder)
    register_decoder("wma", True, RawDecoder)
    register_decoder("aac", True, RawDecoder)

register_decoder()
